package com.bizzard.system.service.impl;

import com.bizzard.system.domain.Role;
import com.bizzard.system.mapper.RoleMapper;
import com.bizzard.system.service.IRoleService;
import com.bizzard.basic.service.impl.BaseServiceImpl;
import com.mysql.jdbc.UpdatableResultSet;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    //添加重构
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addData(role);
    }

    //修改重构
    @Override
    @Transactional
    public void update(Role role) {
        //先删除旧权限
        roleMapper.delRoleMenuByRoleId(role.getId());
        roleMapper.delRolePermissionByRoleId(role.getId());
        //再添加新的权限
        addData(role);
        super.update(role);
    }

    //删除重构
    @Override
    @Transactional
    public void del(Long id) { //id是角色id
        //删除中间表数据
        roleMapper.delRoleMenuByRoleId(id);
        roleMapper.delRolePermissionByRoleId(id);
        roleMapper.delEmployeeRoleByRoleId(id);
        super.del(id);
    }

    //批量删除重构
    @Override
    public void patchDelete(List<Long> ids) {
        for (Long id : ids) {
            del(id);
        }
    }

    //抽取公共方法供添加和修改的时候调用
    private void addData(Role role){
        List<Long> menus = role.getMenus();
        if(menus.size() >0 ){
            roleMapper.addRoleMenu(role.getId(),menus);
        }
        List<Long> permissions = role.getPermissions();
        if(permissions.size() >0 ){
            roleMapper.addRolePermissions(role.getId(),permissions);
        }
    }
}
